package com.atguigu.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author wx
 * @version 1.0
 * @description: TODO
 * @date 2024/11/7 10:31
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    //redis客户端
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 前置拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求中获取token
        String token = request.getHeader("token");
        //如果是预检请求options
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        if (StrUtil.isEmpty(token)) {
            //token不存在 表示用户没有登录设置响应内容
            responseNoLoginInfo(response);
            return false;
        } else {
            //token不为空 从redis中获取数据
            String strUser = redisTemplate.opsForValue().get("user:login:" + token);
            //判断user信息是否为空
            if (StrUtil.isEmpty(strUser)) {
                responseNoLoginInfo(response);
                return false;
            }
            //token不为空
            SysUser sysUser = JSON.parseObject(strUser, SysUser.class);
            //将sysUser存储到线程变量中
            AuthContextUtil.set(sysUser);
            //更新redis时间
            redisTemplate.expire("user:login:" + token, 50000, TimeUnit.MINUTES);
            //放行请求
            return true;
        }
    }

    /**
     * 构建响应信息
     *
     * @param response
     */
    private void responseNoLoginInfo(HttpServletResponse response) {
        //构建响应内容
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        //中文处理
        response.setContentType("text/html;charset=utf-8");
        //响应内容写出
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空线程变量
        AuthContextUtil.remove();
    }
}
